package cmd

import (
	"github.com/apulis/bmod/file-server/configs"
	"github.com/apulis/bmod/file-server/internal/router"
	"github.com/apulis/sdk/go-utils/logging"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"os"
	"os/signal"
	"syscall"
)

// runCmd represents the command to run file server
var runCmd = &cobra.Command{
	Use:   "run",
	Short: "start file server",
	Run: func(cmd *cobra.Command, args []string) {
		configs.Init()
		config := configs.Config

		e := gin.Default()
		router.RegisterRoutes(e)
		go func() {
			if err := e.Run(":" + config.Port); err != nil {
				logging.Fatal().Err(err).Msg("failed to start file service")
			}
		}()

		// Wait for interrupt signal to gracefully shutdown the server with
		// a timeout of 5 seconds.
		quit := make(chan os.Signal)
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit

		logging.Info().Msg("Shutting down file server...")
	},
}

func init() {
	rootCmd.AddCommand(runCmd)
}
